// 腾讯地图API密钥
export const QQMAP_KEY = 'IP6BZ-VFXHT-SJIXQ-LOD5I-FUOXF-J7BPV';

// 获取IP定位信息
export const fetchLocationByIP = async () => {
  try {
    const response = await uni.request({
      url: `https://apis.map.qq.com/ws/location/v1/ip?key=${QQMAP_KEY}`,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      }
    });
    
    console.log('IP定位API响应:', response);
    
    let responseData = null;
    // 处理不同格式的响应
    if (Array.isArray(response) && response.length >= 2) {
      responseData = response[1];
    } else if (typeof response === 'object' && response !== null) {
      responseData = response.data || response;
    }
    
    if (!responseData || (responseData.status !== 0 && responseData.status !== '0') || !responseData.result || !responseData.result.location) {
      throw new Error('IP定位API响应数据异常');
    }
    
    return {
      lat: responseData.result.location.lat,
      lng: responseData.result.location.lng
    };
  } catch (error) {
    console.error('获取IP定位失败:', error);
    throw error;
  }
};

// 获取逆地理编码信息
export const fetchReverseGeocode = async (lat, lng) => {
  try {
    const response = await uni.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${QQMAP_KEY}`,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      }
    });
    
    console.log('逆地理编码API响应:', response);
    
    let responseData = null;
    // 处理不同格式的响应
    if (Array.isArray(response) && response.length >= 2) {
      responseData = response[1];
    } else if (typeof response === 'object' && response !== null) {
      responseData = response.data || response;
    }
    
    if (!responseData || (responseData.status !== 0 && responseData.status !== '0') || !responseData.result || !responseData.result.address_component) {
      return '定位成功';
    }
    
    const addressInfo = responseData.result.address_component;
    return `${addressInfo.city || ''}${addressInfo.district || ''}${addressInfo.street || ''}`;
  } catch (error) {
    console.error('逆地理编码失败:', error);
    return '定位成功';
  }
};